package com.mango.iot.gateway.http.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.mango.iot.gateway.http.consts.CommonConstant;
import com.mango.iot.gateway.http.consts.JsonResult;
import com.mango.iot.gateway.http.consts.ResultCode;
import com.mango.iot.gateway.http.srv.TokenService;
import com.mango.iot.gateway.http.srv.dto.DeviceInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，登录检查
 *
 * @author liangfeihu
 * @since 2023/6/29 14:33
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader(CommonConstant.TOKEN_HEADER);
        if (StringUtils.isNotBlank(token)) {
            DeviceInfo deviceInfo = tokenService.getDeviceInfoInCache(token);
            if (deviceInfo != null) {
                return true;
            } else {
                response.setHeader("Content-Type", "application/json");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write(JSON.toJSONString(JsonResult.error(ResultCode.TOKEN_INVALID)));
                return false;
            }
        }

        response.setHeader("Content-Type", "application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(JSON.toJSONString(JsonResult.error(ResultCode.REQ_FORBIDDEN)));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {}

}
